package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*全局过滤器*/
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断当前请求是否为登录请求 是登录页面放行 ==>
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //获取请求地址  URl
        String path = request.getURI().getPath();
        if (path.contains("/login")) {
            //判断当前path  是否包含 login  包含则证明为登录页面 放行
            return chain.filter(exchange);
        }//执行到此处为 不是登录页面
        //获取当前请求头并判断当前请求头中是否含有token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //如果不含token
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回状态码给浏览器
            return response.setComplete();
        }//到此处为含有token   但是需要判断是否有效 和数据库是否匹配
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        //获取到一个map  根据map进行校验
        int status = AppJwtUtil.verifyToken(claimsBody);
        //返回状态码
        if (status==-1||status==0) {
            //解析成功   把userId和name 放入到请求头中
            Integer userId = claimsBody.get("userId", Integer.class);
            String name = claimsBody.get("name", String.class);
            request.mutate().header("userId",userId.toString());
            request.mutate().header("name",name);
            //继续进入到后面的微服务中
            return chain.filter(exchange);
        }//token 无效
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
        //过滤器执行顺序  数字越小 执行优先 一般默认
    }
}
